package com.foruo.demo.jdbc.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * 利用ThreadLocal来构造在同一个事务下多个sql，只能是同一个connection
 * @author GaoYuan
 */
@Component
public class ThreadLocalPool {

    @Autowired
    MyDataSource myDataSource;

    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    /**
     * 开启事务
     * @author GaoYuan
     */
    public void beginTransation() throws Exception{
        Connection connection = myDataSource.getConnection();
        connection.setAutoCommit(false);
        tl.set(connection);
    }

    /**
     * 获取连接
     * @author GaoYuan
     */
    public Connection getConnection(){
        return tl.get();
    }

    /**
     * 提交事务
     * @author GaoYuan
     */
    public void commit(){
        try {
            tl.get().commit();
        } catch (Exception e) {
        }
        try {
            tl.get().setAutoCommit(true);
        } catch (Exception e) {
        }
    }

    /**
     * 回滚事务
     * @author GaoYuan
     */
    public static void rollback() throws Exception {
        try {
            tl.get().rollback();
        } catch (Exception e) {
        }
        try {
            tl.get().setAutoCommit(true);
        } catch (Exception e) {
        }
    }
}
